package cn.lbd.nioblocking;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class Client {
    public static void main(String[] args) {
        SocketChannel socketChannel = null;
        FileChannel inChannel = null;
        try {
            socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9999));
            inChannel = FileChannel.open(Paths.get("E:\\IO\\demo1\\rinv.jpg"), StandardOpenOption.READ);
            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
            while (inChannel.read(readBuffer) != -1) {
                readBuffer.flip();
                socketChannel.write(readBuffer);
                readBuffer.clear();
            }
            //关闭发送通道，表明发送完毕，否则服务端不知道客户端发送完数据，线程会一直处于阻塞状态
            //处理这个问题有两种方式
            // 1.告诉服务端，客户端已经发完数据 socketChannel.shutdownOutput()
            // 2.把线程切换为非阻塞模式 serverSocketChannel.configureBlocking(false);
            socketChannel.shutdownOutput();
            //接收服务端反馈
            int len = 0;
            while ((len = socketChannel.read(readBuffer)) != -1) {
                readBuffer.flip();
                System.out.println("Server："+new String(readBuffer.array(), 0, len));
                readBuffer.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inChannel != null) {
                    inChannel.close();
                }

                if (socketChannel != null) {
                    socketChannel.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
